﻿using Aspose.Cells;
using Common.Model;
using Common.Platform.Citys.Shandong_Boxing;
using Common.Utility.AJ;
using Common.Utility.AJ.Extension;
using Microsoft.WindowsAPICodePack.Dialogs;
using NPOI.XSSF.UserModel;
using Stylet;
using StyletIoC;
using SUT.PrintEngine.Utils;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Configuration;
using System.Data;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Markup;
using System.Windows.Threading;
using WeighingRecord.Models;
using WeighingRecord.Services;
using WeighingRecord.Views;

namespace WeighingRecord.ViewModels
{
    public class WeightListViewModel : Screen
    {
        //log
        private static readonly log4net.ILog log = LogHelper.GetLogger();

        private IWindowManager windowManager;

        public string SearchText { get; set; }

        private string dateFilter; //日期筛选，0：本日 1：本月 2：自定义
        public string DateFilter
        {
            get
            {
                return dateFilter;
            }
            set
            {
                dateFilter = value;
                if (value.Equals("0"))
                {
                    StartDate = Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-dd"));
                    EndDate = Convert.ToDateTime(DateTime.Now.AddDays(1).ToString("yyyy-MM-dd").ToString()).AddSeconds(-1);
                }
                else if (value.Equals("1"))
                {
                    StartDate = DateTime.Now.AddDays(1 - DateTime.Now.Day).Date;
                    EndDate = DateTime.Now.AddDays(1 - DateTime.Now.Day).Date.AddMonths(1).AddSeconds(-1);
                }
            }
        }
        public DateTime? StartDate { get; set; } //自定义日期筛选的开始日期
        public DateTime? EndDate { get; set; } //自定义日期筛选的结束日期

        public string overloadLog;
        public string OverloadLog
        {
            get { return AppSection.Settings["OverloadLog"].Value; }
            set { overloadLog = value; }
        }

        private bool customerFilter;//是否进行条件筛选客户
        public bool CustomerFilter
        {
            get { return customerFilter; }
            set
            {
                customerFilter = value;
                if (!value)
                    SelectedCustomer = null;
            }
        }

        private bool goodsFilter;//是否进行条件筛选
        public bool GoodsFilter
        {
            get { return goodsFilter; }
            set
            {
                goodsFilter = value;
                if (!value)
                    SelectedGoods = null;
            }
        }

        private bool goodsSpecFilter;//是否进行条件筛选
        public bool GoodsSpecFilter
        {
            get { return goodsSpecFilter; }
            set
            {
                goodsSpecFilter = value;
                if (!value)
                    SelectedGoodsSpec = null;
            }
        }

        private bool weigh2NameFilter;//是否进行条件筛选
        public bool Weigh2NameFilter
        {
            get { return weigh2NameFilter; }
            set
            {
                weigh2NameFilter = value;
                if (!value)
                    SelectedWeigh2Name = null;
            }
        }

        private bool weighNameFilter;//是否进行条件筛选
        public bool WeighNameFilter
        {
            get { return weighNameFilter; }
            set
            {
                weighNameFilter = value;
                if (!value)
                    SelectedWeighName = null;
            }
        }


        private bool carFilter;//是否进行条件筛选
        public bool CarFilter
        {
            get { return carFilter; }
            set
            {
                carFilter = value;
                if (!value)
                    SelectedCar = null;
            }
        }
        private bool by1Filter;//是否进行条件筛选
        public bool By1Filter
        {
            get { return by1Filter; }
            set
            {
                by1Filter = value;
                if (!value)
                    SelectedBy1 = null;
            }
        }
        private bool by2Filter;//是否进行条件筛选
        public bool By2Filter
        {
            get { return by2Filter; }
            set
            {
                by2Filter = value;
                if (!value)
                    SelectedBy2 = null;
            }
        }
        private bool by3Filter;//是否进行条件筛选
        public bool By3Filter
        {
            get { return by3Filter; }
            set
            {
                by3Filter = value;
                if (!value)
                    SelectedBy3 = null;
            }
        }
        private bool by4Filter;//是否进行条件筛选
        public bool By4Filter
        {
            get { return by4Filter; }
            set
            {
                by4Filter = value;
                if (!value)
                    SelectedBy4 = null;
            }
        }
        private bool by5Filter;//是否进行条件筛选
        public bool By5Filter
        {
            get { return by5Filter; }
            set
            {
                by5Filter = value;
                if (!value)
                    SelectedBy5 = null;
            }
        }

        private bool by6Filter;//是否进行条件筛选
        public bool By6Filter
        {
            get { return by6Filter; }
            set
            {
                by6Filter = value;
                if (!value)
                    SelectedBy6 = null;
            }
        }

        private bool by7Filter;//是否进行条件筛选
        public bool By7Filter
        {
            get { return by7Filter; }
            set
            {
                by7Filter = value;
                if (!value)
                    SelectedBy7 = null;
            }
        }

        private bool by8Filter;//是否进行条件筛选
        public bool By8Filter
        {
            get { return by8Filter; }
            set
            {
                by8Filter = value;
                if (!value)
                    SelectedBy8 = null;
            }
        }

        private bool by9Filter;//是否进行条件筛选
        public bool By9Filter
        {
            get { return by9Filter; }
            set
            {
                by9Filter = value;
                if (!value)
                    SelectedBy9 = null;
            }
        }

        private bool by10Filter;//是否进行条件筛选
        public bool By10Filter
        {
            get { return by10Filter; }
            set
            {
                by10Filter = value;
                if (!value)
                    SelectedBy10 = null;
            }
        }

        private bool by11Filter;//是否进行条件筛选
        public bool By11Filter
        {
            get { return by11Filter; }
            set
            {
                by11Filter = value;
                if (!value)
                    SelectedBy11 = null;
            }
        }

        private bool by12Filter;//是否进行条件筛选
        public bool By12Filter
        {
            get { return by12Filter; }
            set
            {
                by12Filter = value;
                if (!value)
                    SelectedBy12 = null;
            }
        }

        private bool by13Filter;//是否进行条件筛选
        public bool By13Filter
        {
            get { return by13Filter; }
            set
            {
                by13Filter = value;
                if (!value)
                    SelectedBy13 = null;
            }
        }

        private bool by14Filter;//是否进行条件筛选
        public bool By14Filter
        {
            get { return by14Filter; }
            set
            {
                by14Filter = value;
                if (!value)
                    SelectedBy14 = null;
            }
        }

        private bool by15Filter;//是否进行条件筛选
        public bool By15Filter
        {
            get { return by15Filter; }
            set
            {
                by15Filter = value;
                if (!value)
                    SelectedBy15 = null;
            }
        }

        private bool by16Filter;//是否进行条件筛选
        public bool By16Filter
        {
            get { return by16Filter; }
            set
            {
                by16Filter = value;
                if (!value)
                    SelectedBy16 = null;
            }
        }

        private bool by17Filter;//是否进行条件筛选
        public bool By17Filter
        {
            get { return by17Filter; }
            set
            {
                by17Filter = value;
                if (!value)
                    SelectedBy17 = null;
            }
        }

        private bool by18Filter;//是否进行条件筛选
        public bool By18Filter
        {
            get { return by18Filter; }
            set
            {
                by18Filter = value;
                if (!value)
                    SelectedBy18 = null;
            }
        }

        private bool by19Filter;//是否进行条件筛选
        public bool By19Filter
        {
            get { return by19Filter; }
            set
            {
                by19Filter = value;
                if (!value)
                    SelectedBy19 = null;
            }
        }

        private bool by20Filter;//是否进行条件筛选
        public bool By20Filter
        {
            get { return by20Filter; }
            set
            {
                by20Filter = value;
                if (!value)
                    SelectedBy20 = null;
            }
        }

        private bool gblxFilter;//是否进行条件筛选
        public bool GblxFilter
        {
            get { return gblxFilter; }
            set
            {
                gblxFilter = value;
                if (!value)
                    SelectedGblx = null;
            }
        }

        private bool zsFilter;//是否进行条件筛选
        public bool ZSFilter
        {
            get { return zsFilter; }
            set
            {
                zsFilter = value;
                if (!value)
                    SelectedZS = null;
            }
        }

        private bool jeFilter;//是否进行条件筛选
        public bool JeFilter
        {
            get { return jeFilter; }
            set
            {
                jeFilter = value;
                if (!value)
                    SelectedJe = null;
            }
        }

        private bool kh2Filter;//是否进行条件筛选
        public bool Kh2Filter
        {
            get { return kh2Filter; }
            set
            {
                kh2Filter = value;
                if (!value)
                    SelectedKh2 = null;
            }
        }
        private bool kh3Filter;//是否进行条件筛选
        public bool Kh3Filter
        {
            get { return kh3Filter; }
            set
            {
                kh3Filter = value;
                if (!value)
                    SelectedKh3 = null;
            }
        }
        private bool weighFormFilter;//是否进行条件筛选
        public bool WeighFormFilter
        {
            get { return weighFormFilter; }
            set
            {
                weighFormFilter = value;
                if (!value)
                    SelectedWeighForm = null;
            }
        }

        private bool mzFilter;//是否进行条件筛选
        public bool MzFilter
        {
            get { return mzFilter; }
            set
            {
                mzFilter = value;
                if (!value)
                    SelectedMz = null;
            }
        }

        private bool pzFilter;//是否进行条件筛选
        public bool PzFilter
        {
            get { return pzFilter; }
            set
            {
                pzFilter = value;
                if (!value)
                    SelectedPz = null;
            }
        }

        private bool jzFilter;//是否进行条件筛选
        public bool JzFilter
        {
            get { return jzFilter; }
            set
            {
                jzFilter = value;
                if (!value)
                    SelectedJz = null;
            }
        }

        private bool mzrqFilter;//是否进行条件筛选
        public bool MzrqFilter
        {
            get { return mzrqFilter; }
            set
            {
                mzrqFilter = value;
                if (!value)
                    SelectedMzrq = null;
            }
        }

        private bool pzrqFilter;//是否进行条件筛选
        public bool PzrqFilter
        {
            get { return pzrqFilter; }
            set
            {
                pzrqFilter = value;
                if (!value)
                    SelectedPzrq = null;
            }
        }

        private bool jzrqFilter;//是否进行条件筛选
        public bool JzrqFilter
        {
            get { return jzrqFilter; }
            set
            {
                jzrqFilter = value;
                if (!value)
                    SelectedJzrq = null;
            }
        }

        private bool mzsbyFilter;//是否进行条件筛选
        public bool MzsbyFilter
        {
            get { return mzsbyFilter; }
            set
            {
                mzsbyFilter = value;
                if (!value)
                    SelectedMzsby = null;
            }
        }

        private bool pzsbyFilter;//是否进行条件筛选
        public bool PzsbyFilter
        {
            get { return pzsbyFilter; }
            set
            {
                pzsbyFilter = value;
                if (!value)
                    SelectedPzsby = null;
            }
        }

        private bool kzFilter;//是否进行条件筛选
        public bool KzFilter
        {
            get { return kzFilter; }
            set
            {
                kzFilter = value;
                if (!value)
                    SelectedKz = null;
            }
        }

        private bool klFilter;//是否进行条件筛选
        public bool KlFilter
        {
            get { return klFilter; }
            set
            {
                klFilter = value;
                if (!value)
                    SelectedKl = null;
            }
        }

        private bool szFilter;//是否进行条件筛选
        public bool SzFilter
        {
            get { return szFilter; }
            set
            {
                szFilter = value;
                if (!value)
                    SelectedSz = null;
            }
        }

        private bool bzFilter;//是否进行条件筛选
        public bool BzFilter
        {
            get { return bzFilter; }
            set
            {
                bzFilter = value;
                if (!value)
                    SelectedBz = null;
            }
        }

        private bool czjeFilter;//是否进行条件筛选
        public bool CzjeFilter
        {
            get { return czjeFilter; }
            set
            {
                czjeFilter = value;
                if (!value)
                    SelectedCzje = null;
            }
        }

        private bool sxedFilter;//是否进行条件筛选
        public bool SxedFilter
        {
            get { return sxedFilter; }
            set
            {
                sxedFilter = value;
                if (!value)
                    SelectedSxed = null;
            }
        }

        private bool gmzlFilter;//是否进行条件筛选
        public bool GmzlFilter
        {
            get { return gmzlFilter; }
            set
            {
                gmzlFilter = value;
                if (!value)
                    SelectedGmzl = null;
            }
        }

        private bool iCCardFilter;//是否进行条件筛选
        public bool ICCardFilter
        {
            get { return iCCardFilter; }
            set
            {
                iCCardFilter = value;
                if (!value)
                    SelectedICCard = null;
            }
        }

        private bool fhdwFilter;//是否进行条件筛选
        public bool FhdwFilter
        {
            get { return fhdwFilter; }
            set
            {
                fhdwFilter = value;
                if (!value)
                    SelectedFhdw = null;
            }
        }

        public BindableCollection<CustomerModel> CustomerList { get; set; } //条件筛选客户下拉列表
        public BindableCollection<GoodsModel> GoodsList { get; set; } //条件筛选物资下拉列表
        public BindableCollection<Common.Models.GoodsSpecModel> GoodsSpecList { get; set; } //条件筛选物资下拉列表
        public BindableCollection<CarModel> CarList { get; set; } //条件筛选车辆下拉列表
        public List<string> WeighNameList { get; set; } //条件筛选磅秤1下拉列表
        public List<string> Weigh2NameList { get; set; } //条件筛选磅秤2下拉列表
        public List<string> By1List { get; set; }
        public List<string> By2List { get; set; }
        public List<string> By3List { get; set; }
        public List<string> By4List { get; set; }
        public List<string> By5List { get; set; }
        public List<string> By6List { get; set; }
        public List<string> By7List { get; set; }
        public List<string> By8List { get; set; }
        public List<string> By9List { get; set; }
        public List<string> By10List { get; set; }
        public List<string> By11List { get; set; }
        public List<string> By12List { get; set; }
        public List<string> By13List { get; set; }
        public List<string> By14List { get; set; }
        public List<string> By15List { get; set; }
        public List<string> By16List { get; set; }
        public List<string> By17List { get; set; }
        public List<string> By18List { get; set; }
        public List<string> By19List { get; set; }
        public List<string> By20List { get; set; }

        //数据读取下拉 存疑，这样查询，会导致性能慢
        public List<string> MzList { get; set; }
        public List<string> PzList { get; set; }
        public List<string> JzList { get; set; }
        public List<string> MzrqList { get; set; }
        public List<string> PzrqList { get; set; }
        public List<string> JzrqList { get; set; }
        public List<string> MzsbyList { get; set; }
        public List<string> PzsbyList { get; set; }
        public List<string> KzList { get; set; }
        public List<string> KlList { get; set; }
        public List<string> SzList { get; set; }
        public List<string> BzList { get; set; }
        public List<string> JeList { get; set; }
        public List<string> CzjeList { get; set; }
        public List<string> SxedList { get; set; }
        public List<string> GmzlList { get; set; }
        public List<string> ICCardList { get; set; }
        public List<string> FhdwList { get; set; }

        //public Dictionary<string, string> GblxDictionary { get; set; } = new Dictionary<string, string>();
        //public Dictionary<string, string> ZSDictionary { get; set; } = new Dictionary<string, string>();
        public List<string> GblxDictionary { get; set; } = new List<string>() { "销售", "采购", "其他" };
        public List<string> ZSDictionary { get; set; } = new List<string>() { "2", "3", "4", "5", "6" };
        public List<string> WeighFormList { get; set; } = new List<string> { "磅单1", "磅单2" };

        public CustomerModel SelectedCustomer { get; set; } //条件筛选选中的客户
        public GoodsModel SelectedGoods { get; set; } //条件筛选选中的物资
        public Common.Models.GoodsSpecModel SelectedGoodsSpec { get; set; } //条件筛选选中的物资g规格
        public CarModel SelectedCar { get; set; } //条件筛选选中的车辆
        public string SelectedWeighName { get; set; }
        public string SelectedWeigh2Name { get; set; }
        public string SelectedBy1 { get; set; }
        public string SelectedBy2 { get; set; }
        public string SelectedBy3 { get; set; }
        public string SelectedBy4 { get; set; }
        public string SelectedBy5 { get; set; }
        public string SelectedBy6 { get; set; }
        public string SelectedBy7 { get; set; }
        public string SelectedBy8 { get; set; }
        public string SelectedBy9 { get; set; }
        public string SelectedBy10 { get; set; }
        public string SelectedBy11 { get; set; }
        public string SelectedBy12 { get; set; }
        public string SelectedBy13 { get; set; }
        public string SelectedBy14 { get; set; }
        public string SelectedBy15 { get; set; }
        public string SelectedBy16 { get; set; }
        public string SelectedBy17 { get; set; }
        public string SelectedBy18 { get; set; }
        public string SelectedBy19 { get; set; }
        public string SelectedBy20 { get; set; }
        public string SelectedGblx { get; set; }
        public string SelectedZS { get; set; }

        public string SelectedJe { get; set; }
        public string SelectedMz { get; set; }
        public string SelectedPz { get; set; }
        public string SelectedJz { get; set; }
        public string SelectedMzrq { get; set; }
        public string SelectedPzrq { get; set; }
        public string SelectedJzrq { get; set; }
        public string SelectedMzsby { get; set; }
        public string SelectedPzsby { get; set; }
        public string SelectedKz { get; set; }
        public string SelectedKl { get; set; }
        public string SelectedSz { get; set; }
        public string SelectedBz { get; set; }
        public string SelectedCzje { get; set; }
        public string SelectedSxed { get; set; }
        public string SelectedGmzl { get; set; }
        public string SelectedICCard { get; set; }
        public string SelectedFhdw { get; set; }
        public string SelectedWeighForm { get; set; }
        public CustomerModel SelectedKh2 { get; set; } //条件筛选选中的客户
        public CustomerModel SelectedKh3 { get; set; } //条件筛选选中的客户

        public DataTable RecordDT { get; private set; } //经过转换的称重记录表格，用来显示到列表、导出到excel
        private DataRowView selectedRecrod;
        public DataRowView SelectedRecrod
        {
            get
            {
                return selectedRecrod;
            }
            set
            {
                selectedRecrod = value;
                if (selectedRecrod == null) return;

                var bh = SelectedRecrod.Row.ItemArray[0].ToString();
                if (!string.IsNullOrWhiteSpace(bh))
                {
                    var record = SQLDataAccess.GetByBH(bh);
                    if (record != null && record.Valid)//正常数据
                    {
                        ButtonVisible = Visibility.Visible;
                        DelBtnText = "作废选中";
                    }
                    else//删除的数据
                    {
                        ButtonVisible = Visibility.Collapsed;
                        DelBtnText = "取消作废";
                    }
                }
                else
                {
                    ButtonVisible = Visibility.Visible;
                    DelBtnText = "作废选中";
                }

            }
        } //选中的称重记录，补充打印用

        /// <summary>
        /// 重新上传按钮可见性 --阿吉 2023年7月14日11点35分
        /// </summary>
        public Visibility ReUploadButtonVisible { get; set; } = Visibility.Collapsed;

        public System.Windows.Visibility ButtonVisible { get; set; } = System.Windows.Visibility.Visible;//当选中删除的记录时，需要将其他的按钮隐藏的标记
        public string DelBtnText { get; set; } = "作废选中";//当选中了删除数据后，这个文本就要变成“取消作废”，当选择的是正常的数据时，这个文本就是“作废选中”。
        public string UnfinishedReportData { get; set; }
        public string ReportData { get; set; }
        public string StatusBar { get; set; }
        public Dictionary<string, string> TemplateFieldDic { get; set; } = new Dictionary<string, string>();
        public BindableCollection<string> SelectedItems { get; set; } = new BindableCollection<string>(); //选择的显示字段
        public List<WeighingRecordModel> WList { get; private set; } = new List<WeighingRecordModel>(); //从数据库中查询出的原始称重记录列表
        public int SelectedTotalWeighingCount { get; private set; }
        public decimal SelectedTotalJz { get; private set; }
        public decimal SelectedTotalSz { get; private set; }
        public string WeighingUnit { get; }
        public Worksheet Worksheet { get; }
        public AppSettingsSection AppSection { get; } = (AppSettingsSection)ConfigurationManager.OpenExeConfiguration("衡七管家.exe").GetSection("appSettings");

        public bool HaveBy1 { get; set; }
        public bool HaveBy2 { get; set; }
        public bool HaveBy3 { get; set; }
        public bool HaveBy4 { get; set; }
        public bool HaveBy5 { get; set; }
        public bool HaveBy6 { get; set; }
        public bool HaveBy7 { get; set; }
        public bool HaveBy8 { get; set; }
        public bool HaveBy9 { get; set; }
        public bool HaveBy10 { get; set; }
        public bool HaveBy11 { get; set; }
        public bool HaveBy12 { get; set; }
        public bool HaveBy13 { get; set; }
        public bool HaveBy14 { get; set; }
        public bool HaveBy15 { get; set; }
        public bool HaveBy16 { get; set; }
        public bool HaveBy17 { get; set; }
        public bool HaveBy18 { get; set; }
        public bool HaveBy19 { get; set; }
        public bool HaveBy20 { get; set; }
        public bool HaveGblx { get; set; }
        public bool HaveZS { get; set; }
        public bool HaveKh { get; set; }
        public bool HaveKh2 { get; set; }
        public bool HaveKh3 { get; set; }


        public bool HaveCh { get; set; }
        public bool HaveWz { get; set; }
        public bool HaveGg { get; set; }
        public bool HaveMz { get; set; }
        public bool HavePz { get; set; }
        public bool HaveJz { get; set; }
        public bool HaveMzrq { get; set; }
        public bool HavePzrq { get; set; }
        public bool HaveJzrq { get; set; }
        public bool HaveMzsby { get; set; }
        public bool HavePzsby { get; set; }
        public bool HaveKz { get; set; }
        public bool HaveKl { get; set; }
        public bool HaveSz { get; set; }
        public bool HaveBz { get; set; }
        public bool HaveCzje { get; set; }
        public bool HaveSxed { get; set; }
        public bool HaveGmzl { get; set; }
        public bool HaveJe { get; set; }
        public bool HaveICCard { get; set; }
        public bool HaveFhdw { get; set; }
        public bool HaveWeighName { get; set; }
        public bool HaveWeigh2Name { get; set; }

        private bool selectAll;
        public bool SelectAll
        {
            get
            {
                return selectAll;
            }
            set
            {
                selectAll = value;
                // SetAndNotify(ref selectAll, value);
            }
        }

        public bool Unfinished { get; set; } = false;
        public bool OverLimit { get; set; } = false;
        public bool IsDel { get; set; } = false;
        /// <summary>
        /// 是否显示修改前数据，这里使用 By20 字段存储， 1 表示是备份的数据
        /// </summary>
        public bool By20 { get; set; } = false;

        public bool EnableQueryList { get; set; } = false;
        public bool EnablePrintList { get; set; } = false;
        public bool EnableExportList { get; set; } = false;
        public bool EnableDeleteList { get; set; } = false;
        public bool EnableUpdateSelected { get; set; } = false;
        public bool EnableDeleteSelected { get; set; } = false;
        public bool EnablePrintSelected { get; set; } = false;
        public bool EnableInsertItem { get; set; } = false;

        public bool EnableUpdatePz { get; set; } = false;
        public bool EnableUpdateMz { get; set; } = false;
        public bool EnableUpdateJz { get; set; } = false;
        public bool EnableUpdateSz { get; set; } = false;

        public bool FlitAbnormalData { get; set; }
        public string MinAbnormalData { get; set; }
        public string MaxAbnormalData { get; set; }

        public bool SimpleMode { get; set; } = false;

        private DispatcherTimer autoCheckTimer = new DispatcherTimer();

        private bool autoCheck;
        public bool AutoCheck
        {
            get { return autoCheck; }
            set
            {
                autoCheck = value;

                if (value)
                {
                    autoCheckTimer.Start();
                }
                else
                {
                    autoCheckTimer.Stop();
                }
            }
        }

        private ListBox _list_box_columns;

        private string _platformName;

        public List<WeighingRecordModel> NotUploadedRecords { get; set; }

        public WeightListViewModel(IWindowManager windowManager)
        {

            _platformName = Common.Utility.SettingsHelper.AWSV2Settings.Settings["PlatformName"]?.Value ?? "Default";
            Common.Platform.PlatformManager.LOGGER = log;
            Common.Platform.PlatformManager.Instance.Init(_platformName);

            var isDefaultPlatform = _platformName.Equals("default", StringComparison.OrdinalIgnoreCase);

            if (!isDefaultPlatform)
            {
                NotUploadedRecords = SQLDataAccess.LoadWeighingRecordByUploadFlag(false);
            }

            ReUploadButtonVisible = !isDefaultPlatform && NotUploadedRecords.Count > 0
                 ? Visibility.Visible : Visibility.Collapsed;
            this.windowManager = windowManager;
            //初始化日期筛选选择本日
            DateFilter = "0";

            //初始化条件筛选下拉框内容列表
            CustomerList = new BindableCollection<CustomerModel>(SQLDataAccess.LoadActiveCustomer(2));
            GoodsList = new BindableCollection<GoodsModel>(SQLDataAccess.LoadActiveGoods(2));
            GoodsSpecList = new BindableCollection<Common.Models.GoodsSpecModel>(Common.Data.SQLDataAccess.GetGoodsSpecs());
            CarList = new BindableCollection<CarModel>(SQLDataAccess.LoadActiveCar(2));
            By1List = SQLDataAccess.LoadByxValue("By1");
            By2List = SQLDataAccess.LoadByxValue("By2");
            By3List = SQLDataAccess.LoadByxValue("By3");
            By4List = SQLDataAccess.LoadByxValue("By4");
            By5List = SQLDataAccess.LoadByxValue("By5");
            By6List = SQLDataAccess.LoadByxValue("By6");
            By7List = SQLDataAccess.LoadByxValue("By7");
            By8List = SQLDataAccess.LoadByxValue("By8");
            By9List = SQLDataAccess.LoadByxValue("By9");
            By10List = SQLDataAccess.LoadByxValue("By10");
            By11List = SQLDataAccess.LoadByxValue("By11");
            By12List = SQLDataAccess.LoadByxValue("By12");
            By13List = SQLDataAccess.LoadByxValue("By13");
            By14List = SQLDataAccess.LoadByxValue("By14");
            By15List = SQLDataAccess.LoadByxValue("By15");
            By16List = SQLDataAccess.LoadByxValue("By16");
            By17List = SQLDataAccess.LoadByxValue("By17");
            By18List = SQLDataAccess.LoadByxValue("By18");
            By19List = SQLDataAccess.LoadByxValue("By19");
            By20List = SQLDataAccess.LoadByxValue("By20");
            WeighNameList = Common.Data.SQLDataAccess.GetWeighNames("weighname");
            Weigh2NameList = Common.Data.SQLDataAccess.GetWeighNames("weigh2name");

            MzList = SQLDataAccess.LoadByxValue("Mz");
            PzList = SQLDataAccess.LoadByxValue("Pz");
            JzList = SQLDataAccess.LoadByxValue("Jz");
            MzrqList = SQLDataAccess.LoadByxValue("Mzrq");
            PzrqList = SQLDataAccess.LoadByxValue("Pzrq");
            JzrqList = SQLDataAccess.LoadByxValue("Jzrq");
            MzsbyList = SQLDataAccess.LoadByxValue("Mzsby");
            PzsbyList = SQLDataAccess.LoadByxValue("Pzsby");
            KzList = SQLDataAccess.LoadByxValue("Kz");
            KlList = SQLDataAccess.LoadByxValue("Kl");
            SzList = SQLDataAccess.LoadByxValue("Sz");
            BzList = SQLDataAccess.LoadByxValue("Bz");
            JeList = SQLDataAccess.LoadByxValue("Je");
            CzjeList = SQLDataAccess.LoadByxValue("Amount");
            SxedList = SQLDataAccess.LoadByxValue("Credit");
            GmzlList = SQLDataAccess.LoadByxValue("Weigh");
            ICCardList = SQLDataAccess.LoadByxValue("ICCard");
            FhdwList = SQLDataAccess.LoadByxValue("Fhdw");

            WeighingUnit = AppSection.Settings["WeighingUnit"].Value;
            var printTemplate = AppSection.Settings["PrintTemplate"].Value;

            //根据过磅单初始化显示字段列表
            try
            {
                //打开过磅单模板
                if (printTemplate == "1") Worksheet = new Workbook(Globalspace._weightFormTemplatePath).Worksheets[0];
                if (printTemplate == "2") Worksheet = new Workbook(Globalspace._weightFormTemplatePath).Worksheets[1];
                if (printTemplate == "3") Worksheet = new Workbook(Globalspace._weightFormTemplatePath).Worksheets[2];

                //设置查找区域：有内容的区域
                var range = Worksheet.Cells.MaxDisplayRange;
                string cellRange = range.RefersTo.Split('!')[1].Replace("$", "");
                string startCellName = cellRange.Split(':')[0];
                string endCellName = cellRange.Split(':')[1];
                CellArea area = CellArea.CreateCellArea(startCellName, endCellName);
                //查找规则
                FindOptions opts = new FindOptions();
                opts.LookInType = LookInType.Values;
                opts.LookAtType = LookAtType.Contains;
                opts.SetRange(area);

                Cell cell = null;
                do
                {
                    // Search the cell contain value search within range
                    cell = Worksheet.Cells.Find("_", cell, opts);

                    // If no such cell found, then break the loop
                    if (cell == null)
                        break;

                    string key = cell.Value.ToString();
                    var dic = new Dictionary<string, string>();
                    if (AppSection.Settings[cell.Value.ToString()] != null && !dic.ContainsKey(key))
                    {
                        dic.Add(cell.Value.ToString(), AppSection.Settings[cell.Value.ToString()].Value);
                    }
                    //此处删掉DIC中的编号字段，在后面Datatable中再添加，放到第一列
                    if (dic.ContainsKey("_bh"))
                    {
                        dic.Remove("_bh");
                    }
                    if (dic.ContainsKey("_dyrq"))
                    {
                        dic.Remove("_dyrq");
                    }
                    var orderedDic = dic.OrderBy(p => p.Value).Select(p => new
                    {
                        p.Key,
                        p.Value
                    }).ToList();
                    foreach (var item in orderedDic)
                    {
                        if (!TemplateFieldDic.ContainsKey(item.Key))
                        {
                            TemplateFieldDic.Add(item.Key, item.Value);
                        }
                    }

                    //这些字段非磅单里的，所以固定显示
                    HaveWeighName = true;
                    HaveWeigh2Name = true;
                    //固定显示结束

                    if (cell.Value.ToString() == "_by1") HaveBy1 = true;
                    if (cell.Value.ToString() == "_by2") HaveBy2 = true;
                    if (cell.Value.ToString() == "_by3") HaveBy3 = true;
                    if (cell.Value.ToString() == "_by4") HaveBy4 = true;
                    if (cell.Value.ToString() == "_by5") HaveBy5 = true;
                    if (cell.Value.ToString() == "_by6") HaveBy6 = true;
                    if (cell.Value.ToString() == "_by7") HaveBy7 = true;
                    if (cell.Value.ToString() == "_by8") HaveBy8 = true;
                    if (cell.Value.ToString() == "_by9") HaveBy9 = true;
                    if (cell.Value.ToString() == "_by10") HaveBy10 = true;
                    if (cell.Value.ToString() == "_by11") HaveBy11 = true;
                    if (cell.Value.ToString() == "_by12") HaveBy12 = true;
                    if (cell.Value.ToString() == "_by13") HaveBy13 = true;
                    if (cell.Value.ToString() == "_by14") HaveBy14 = true;
                    if (cell.Value.ToString() == "_by15") HaveBy15 = true;
                    if (cell.Value.ToString() == "_by16") HaveBy16 = true;
                    if (cell.Value.ToString() == "_by17") HaveBy17 = true;
                    if (cell.Value.ToString() == "_by18") HaveBy18 = true;
                    if (cell.Value.ToString() == "_by19") HaveBy19 = true;
                    if (cell.Value.ToString() == "_by20") HaveBy20 = true;
                    if (cell.Value.ToString() == "_gblx") HaveGblx = true;
                    if (cell.Value.ToString() == "_axleNum") HaveZS = true;

                    if (cell.Value.ToString() == "_ch") HaveCh = true;
                    if (cell.Value.ToString() == "_wz") HaveWz = true;
                    if (cell.Value.ToString() == "_goodsSpec") HaveGg = true;


                    if (cell.Value.ToString() == "_kh") HaveKh = true;
                    if (cell.Value.ToString() == "_kh2") HaveKh2 = true;
                    if (cell.Value.ToString() == "_kh3") HaveKh3 = true;
                    if (cell.Value.ToString() == "_jg") HaveJe = true;
                    if (cell.Value.ToString() == "_iccard") HaveICCard = true;
                    if (cell.Value.ToString() == "_fhdw") HaveFhdw = true;


                    if (cell.Value.ToString() == "_mz") HaveMz = true;
                    if (cell.Value.ToString() == "_pz") HavePz = true;
                    if (cell.Value.ToString() == "_jz") HaveJz = true;
                    if (cell.Value.ToString() == "_mzrq") HaveMzrq = true;
                    if (cell.Value.ToString() == "_pzrq") HavePzrq = true;
                    if (cell.Value.ToString() == "_jzrq") HaveJzrq = true;
                    if (cell.Value.ToString() == "_mzsby") HaveMzsby = true;
                    if (cell.Value.ToString() == "_pzsby") HavePzsby = true;
                    if (cell.Value.ToString() == "_kz") HaveKz = true;
                    if (cell.Value.ToString() == "_kl") HaveKl = true;
                    if (cell.Value.ToString() == "_sz") HaveSz = true;
                    if (cell.Value.ToString() == "_bz") HaveBz = true;
                    if (cell.Value.ToString() == "_amount") HaveCzje = true;
                    if (cell.Value.ToString() == "_credit") HaveSxed = true;
                    if (cell.Value.ToString() == "_weigh") HaveGmzl = true;

                } while (true);
            }
            catch (Exception e)
            {
                StatusBar = e.Message;
            }

            autoCheckTimer = new DispatcherTimer { Interval = TimeSpan.FromSeconds(5) };
            autoCheckTimer.Tick += (sender, args) =>
            {
                Console.WriteLine("autoCheckTimer.Tick");
                QueryList();
                SetBtns();
            };

            string rolePermission = SQLDataAccess.LoadLoginRolePermission(Globalspace._currentUserId);
            if (rolePermission != null)
            {
                if (rolePermission.Contains("查询列表")) EnableQueryList = true;
                if (rolePermission.Contains("打印列表")) EnablePrintList = true;
                if (rolePermission.Contains("导出列表")) EnableExportList = true;
                if (rolePermission.Contains("删除列表")) EnableDeleteList = true;
                //if (rolePermission.Contains("修改选中")) EnableUpdateSelected = true;
                if (rolePermission.Contains("修改")) EnableUpdateSelected = true;
                if (rolePermission.Contains("删除选中")) EnableDeleteSelected = true;
                if (rolePermission.Contains("补打选中")) EnablePrintSelected = true;
                if (rolePermission.Contains("手工制单")) EnableInsertItem = true;

                ////默认开启修改选中
                //EnableUpdateSelected = true;

                //if (rolePermission.Contains("修改皮重")) EnableUpdateSelected = EnableUpdatePz = true;
                //if (rolePermission.Contains("修改毛重")) EnableUpdateSelected = EnableUpdateMz = true;
                //if (rolePermission.Contains("修改净重")) EnableUpdateSelected = EnableUpdateJz = true;
                //if (rolePermission.Contains("修改实重")) EnableUpdateSelected = EnableUpdateSz = true;
            }

            //定时刷新Config里的参数
            var timer = new DispatcherTimer { Interval = TimeSpan.FromMilliseconds(5000) };
            timer.Start();
            timer.Tick += (sender, args) =>
            {
                //FlitAbnormalData = Convert.ToBoolean(ConfigurationManager.AppSettings["FlitAbnormalData"]);
                //MinAbnormalData = ConfigurationManager.AppSettings["MinAbnormalData"];
                //MaxAbnormalData = ConfigurationManager.AppSettings["MaxAbnormalData"];

                FlitAbnormalData = Convert.ToBoolean(Common.Utility.SettingsHelper.ZXWeighingRecordSettings.Settings["FlitAbnormalData"].Value);
                MinAbnormalData = Common.Utility.SettingsHelper.ZXWeighingRecordSettings.Settings["MinAbnormalData"].Value;
                MaxAbnormalData = Common.Utility.SettingsHelper.ZXWeighingRecordSettings.Settings["MaxAbnormalData"].Value;
            };

            //初始化分页控件的页行数的大小
            SelectedPageSizeItems = PageSizeItems.FirstOrDefault();
        }

        public void WRecordSelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (sender is DataGrid dg)
            {
                var view = dg.SelectedItem as DataRowView;
                if (view == null)
                {
                    return;
                }
                var bh = view.Row.ItemArray[0].ToString();
                if (!string.IsNullOrWhiteSpace(bh))
                {
                    var match = bh.Contains("X");
                    ButtonVisible = match ? Visibility.Collapsed : Visibility.Visible;
                    EnableDeleteSelected = !match;
                }
            }
        }

        public void By20CheckChanged(object sender, System.Windows.RoutedEventArgs e)
        {
            var checkbox = (CheckBox)sender;

            var isChecked = checkbox.IsChecked.GetValueOrDefault();
            ButtonVisible = isChecked ? Visibility.Collapsed : Visibility.Visible;
            EnableDeleteSelected = !isChecked;
        }

        public void CheckBox_ALL_CheckedChange(object sender, System.Windows.RoutedEventArgs e)
        {
            var checkbox = (CheckBox)sender;
            if (_list_box_columns != null)
            {
                if (checkbox.IsChecked.GetValueOrDefault())
                {
                    if (_list_box_columns.SelectedItems.Count != TemplateFieldDic.Count)
                    {
                        _list_box_columns.SelectedItems.Clear();
                        foreach (var item in TemplateFieldDic)
                        {
                            _list_box_columns.SelectedItems.Add(item.Value);
                        }
                    }


                    //SelectedItems.Clear();
                    //SelectedItems.AddRange(TemplateFieldDic.Values.ToList());
                }
                else
                {
                    if (_list_box_columns.SelectedItems.Count == TemplateFieldDic.Count)
                    {
                        _list_box_columns.SelectedItems.Clear();
                    }


                    //SelectedItems.Clear();
                }
            }

        }

        public void ColumnsChange(object sender, SelectionChangedEventArgs e)
        {
            var ctrl = sender as ListBox;
            if (_list_box_columns == null)
            {
                _list_box_columns = ctrl;
            }
            var items = ctrl.SelectedItems;
            SelectedItems.Clear();
            foreach (string item in items)
            {
                SelectedItems.Add(item);
            }

            SelectAll = SelectedItems.Count == TemplateFieldDic.Values.Count;
        }

        public void QueryList()
        {
            try
            {
                if (SelectedItems.Count == 0)
                {
                    StatusBar = "请选择需要显示的数据";
                    return;
                }

                SelectedTotalWeighingCount = 0;
                SelectedTotalJz = 0;
                SelectedTotalSz = 0;

                //初始化SQL语句的参数，查询数据库得到初始数据
                string Kh = "%";
                string Wz = "%";
                string Gg = "%";
                string Ch = "%";
                string strStartDate = ((DateTime)StartDate).ToString("yyyy-MM-dd HH:mm:ss");
                string strEndDate = ((DateTime)EndDate).ToString("yyyy-MM-dd HH:mm:ss");
                string by1 = "%";
                string by2 = "%";
                string by3 = "%";
                string by4 = "%";
                string by5 = "%";
                string by6 = "%";
                string by7 = "%";
                string by8 = "%";
                string by9 = "%";
                string by10 = "%";
                string by11 = "%";
                string by12 = "%";
                string by13 = "%";
                string by14 = "%";
                string by15 = "%";
                string by16 = "%";
                string by17 = "%";
                string by18 = "%";
                string by19 = "%";
                // 这里的by20已特殊处理，用来筛选备用数据 --阿吉 2023年7月5日15点02分
                string by20 = string.Empty;
                string gblx = "%";
                string zs = "%";

                string kh2 = "%";
                string kh3 = "%";
                string weighName = "%";
                string weigh2Name = "%";

                string mz = "%";
                string pz = "%";
                string jz = "%";
                string mzrq = "%";
                string pzrq = "%";
                string jzrq = "%";
                string mzsby = "%";
                string pzsby = "%";
                string kl = "%";
                string kz = "%";
                string sz = "%";
                string bz = "%";
                string je = "%";
                string czje = "%";
                string sxed = "%";
                string gmzl = "%";
                string fhdw = "%";
                string iccard = "%";

                if (CustomerFilter && SelectedCustomer != null) Kh = SelectedCustomer.Name;
                if (WeighNameFilter && SelectedWeighName != null) weighName = SelectedWeighName;
                if (Weigh2NameFilter && SelectedWeigh2Name != null) weigh2Name = SelectedWeigh2Name;
                if (GoodsFilter && SelectedGoods != null) Wz = SelectedGoods.Name;
                if (GoodsSpecFilter && SelectedGoodsSpec != null) Gg = SelectedGoodsSpec.Name;
                if (CarFilter && SelectedCar != null) Ch = SelectedCar.PlateNo;
                if (by1Filter && SelectedBy1 != null) by1 = SelectedBy1;
                if (by2Filter && SelectedBy2 != null) by2 = SelectedBy2;
                if (by3Filter && SelectedBy3 != null) by3 = SelectedBy3;
                if (by4Filter && SelectedBy4 != null) by4 = SelectedBy4;
                if (by5Filter && SelectedBy5 != null) by5 = SelectedBy5;
                if (by6Filter && SelectedBy6 != null) by6 = SelectedBy6;
                if (by7Filter && SelectedBy7 != null) by7 = SelectedBy7;
                if (by8Filter && SelectedBy8 != null) by8 = SelectedBy8;
                if (by9Filter && SelectedBy9 != null) by9 = SelectedBy9;
                if (by10Filter && SelectedBy10 != null) by10 = SelectedBy10;
                if (by11Filter && SelectedBy11 != null) by11 = SelectedBy11;
                if (by12Filter && SelectedBy12 != null) by12 = SelectedBy12;
                if (by13Filter && SelectedBy13 != null) by13 = SelectedBy13;
                if (by14Filter && SelectedBy14 != null) by14 = SelectedBy14;
                if (by15Filter && SelectedBy15 != null) by15 = SelectedBy15;
                if (by16Filter && SelectedBy16 != null) by16 = SelectedBy16;
                if (by17Filter && SelectedBy17 != null) by17 = SelectedBy17;
                if (by18Filter && SelectedBy18 != null) by18 = SelectedBy18;
                if (by19Filter && SelectedBy19 != null) by19 = SelectedBy19;

                // 这里的by20用来筛选备份数据 --阿吉 2023年7月5日15点01分
                if (By20) by20 = "1";

                if (gblxFilter && SelectedGblx != null) gblx = SelectedGblx;
                if (zsFilter && SelectedZS != null) zs = SelectedZS;
                if (kh2Filter && SelectedKh2 != null) kh2 = SelectedKh2.Name;
                if (kh3Filter && SelectedKh3 != null) kh3 = SelectedKh3.Name;

                if (mzFilter && SelectedMz != null) mz = SelectedMz;
                if (pzFilter && SelectedPz != null) pz = SelectedPz;
                if (jzFilter && SelectedJz != null) jz = SelectedJz;
                if (mzrqFilter && SelectedMzrq != null) mzrq = SelectedMzrq;
                if (pzrqFilter && SelectedPzrq != null) pzrq = SelectedPzrq;
                if (jzrqFilter && SelectedJzrq != null) jzrq = SelectedJzrq;
                if (mzsbyFilter && SelectedMzsby != null) mzsby = SelectedMzsby;
                if (pzsbyFilter && SelectedPzsby != null) pzsby = SelectedPzsby;
                if (kzFilter && SelectedKz != null) kz = SelectedKz;
                if (klFilter && SelectedKl != null) kl = SelectedKl;
                if (szFilter && SelectedSz != null) sz = SelectedSz;
                if (bzFilter && SelectedBz != null) bz = SelectedBz;
                if (jeFilter && SelectedJe != null) je = SelectedJe;
                if (czjeFilter && SelectedCzje != null) czje = SelectedCzje;
                if (sxedFilter && SelectedSxed != null) sxed = SelectedSxed;
                if (gmzlFilter && SelectedGmzl != null) gmzl = SelectedGmzl;
                if (ICCardFilter && SelectedICCard != null) iccard = SelectedICCard;
                if (FhdwFilter && SelectedFhdw != null) fhdw = SelectedFhdw;
                if (WList != null)
                    WList.Clear();

                //if (!string.IsNullOrEmpty(SearchText))
                //{
                //    var txtList = SearchText.Split(',');
                //    foreach (var txt in txtList)
                //    {
                //        if (string.IsNullOrEmpty(txt)) continue;
                //        var tList = SQLDataAccess.LoadWeighingRecord(txt, strStartDate, strEndDate, 1);
                //        WList = WList.Concat(tList).ToList();
                //        if (Unfinished)
                //        {
                //            var unfinishedList = SQLDataAccess.LoadWeighingRecord(txt, strStartDate, strEndDate, 0);
                //            WList = unfinishedList.Concat(WList).ToList();
                //        }
                //    }
                //}
                //else
                {
                    var flag = Unfinished ? new int?(0) : null;
                    var maxAbnormalData = Common.Utility.SettingsHelper.ZXWeighingRecordSettings.Settings["MaxAbnormalData"]?.Value.TryGetDecimal() ?? 100000m;
                    WList = SQLDataAccess.LoadWeighingRecord(
                            Kh, Wz, Ch, strStartDate, strEndDate,
                            by1, by2, by3, by4, by5, by6, by7, by8, by9, by10, by11, by12, by13, by14, by15,
                            by16, by17, by18, by19, by20, kh2, kh3, mz, pz, jz, mzrq, pzrq, jzrq, mzsby, pzsby, kz, kl, sz, bz, je, czje, sxed, gmzl, Gg, fhdw, flag, maxAbnormalData: maxAbnormalData);
                }

                //WList = WList.Distinct(new WeighingRecordComparer()).ToList();

                if (zs != "%")
                {
                    WList = WList.Where(p => p.AxleNum == zs).ToList();
                }

                if (gblx != "%")
                {
                    WList = WList.Where(p => p.Gblx == gblx).ToList();
                }

                if (weighName != "%")
                {
                    WList = WList.Where(p => p.WeighName == weighName).ToList();
                }

                if (weigh2Name != "%")
                {
                    WList = WList.Where(p => p.Weigh2Name == weigh2Name).ToList();
                }

                if (!OverLimit)//过滤掉超载的
                {
                    WList = WList.Where(p => p.IsLimit == false).ToList();
                }
                //if (!IsDel)//过滤掉作废的
                //{
                //    WList = WList.Where(p => p.Valid == true).ToList();
                //}
                if (IsDel)//只显示作废的
                {
                    WList = WList.Where(p => !p.Valid).ToList();
                }
                else
                {
                    WList = WList.Where(p => p.Valid).ToList();
                }

                if (WeighFormFilter && SelectedWeighForm != null)
                {
                    if (SelectedWeighForm == "磅单1")
                    {
                        WList = WList.FindAll(w => w.WeighingFormTemplate == "1");
                    }
                    else if (SelectedWeighForm == "磅单2")
                    {
                        WList = WList.FindAll(w => w.WeighingFormTemplate == "2");
                    }
                }


                WList = WList.OrderByDescending(o => o.AutoNo).ToList();

                //----------分页逻辑开始------
                DataCount = WList.Count;//数据总数
                Pages = (DataCount + PageCount - 1) / PageCount;//总页数
                WList = WList.Skip(PageCount * (CurrentIndex - 1)).Take(PageCount).ToList();
                //SetBtns();
                //----------分页逻辑结束------

                //---------计算报表数据-------
                UnfinishedReportData = string.Empty;
                //UnfinishedReportData += $" 当页未完成：{WList.Where(p =>!p.IsFinish ).Count()} 条 | ";
                UnfinishedReportData += $" 当页未完成：{WList.Where(p => !p.IsFinish).Count()} 条 ";

                ReportData = string.Empty;
                ReportData += $" 当页总毛重：{WList.Where(p => !string.IsNullOrEmpty(p.Mz)).Sum(s => decimal.Parse(s.Mz)).ToString("0.00")} |";
                ReportData += $" 当页总皮重：{WList.Where(p => !string.IsNullOrEmpty(p.Pz)).Sum(s => decimal.Parse(s.Pz)).ToString("0.00")} |";
                ReportData += $" 当页总净重：{WList.Where(p => !string.IsNullOrEmpty(p.Jz)).Sum(s => decimal.Parse(s.Jz)).ToString("0.00")} |";
                ReportData += $" 当页总实重：{WList.Where(p => !string.IsNullOrEmpty(p.Sz)).Sum(s => decimal.Parse(s.Sz)).ToString("0.00")} |";
                ReportData += $" 当页总扣重：{WList.Where(p => !string.IsNullOrEmpty(p.Kz)).Sum(s => decimal.Parse(s.Kz)).ToString("0.00")}";
                //---------计算报表结束-------

                ////处理数据，放入DataTable中
                var dt = new DataTable("WeighingRecord");
                //根据选择的显示字段，构造DataTabel 
                dt.Columns.Add(AppSection.Settings["_bh"].Value);
                //dt.Columns.Add(AppSection.Settings["_weighName"].Value);
                //dt.Columns.Add(AppSection.Settings["_weigh2Name"].Value);


                //dt.Columns.Add("超载");
                //dt.Columns.Add("是否遮挡");
                //dt.Columns.Add("支付方式");
                var orderedColumns = SelectedItems.OrderBy(p => p).ToList();
                foreach (var item in SelectedItems)
                {
                    if (!dt.Columns.Contains(item))
                    {
                        dt.Columns.Add(item);
                    }
                }
                //修改列类型
                foreach (DataColumn col in dt.Columns)
                {
                    if (col.ColumnName == AppSection.Settings["_mz"].Value ||
                        col.ColumnName == AppSection.Settings["_pz"].Value ||
                        col.ColumnName == AppSection.Settings["_jz"].Value ||
                        col.ColumnName == AppSection.Settings["_kz"].Value ||
                        col.ColumnName == AppSection.Settings["_sz"].Value ||
                        col.ColumnName == AppSection.Settings["_dj"].Value ||
                        col.ColumnName == AppSection.Settings["_je"].Value)
                    {
                        col.DataType = typeof(decimal);
                    }
                }

                //APP打开后，再新增到数据库的数据，列表中没有，所以要再查一次
                CustomerList = new BindableCollection<CustomerModel>(SQLDataAccess.LoadActiveCustomer(2));
                GoodsList = new BindableCollection<GoodsModel>(SQLDataAccess.LoadActiveGoods(2));
                CarList = new BindableCollection<CarModel>(SQLDataAccess.LoadActiveCar(2));

                //根据选择的显示字段，处理条件筛选后获得的数据
                foreach (var wr in WList)
                {
                    if (FlitAbnormalData)
                    {
                        if (wr.Jz.TryGetDecimal() < MinAbnormalData.TryGetDecimal()) continue;
                        //if (Convert.ToDecimal(wr.Jz) > Convert.ToDecimal(MaxAbnormalData)) continue;

                        ////显示指定数值内-100的随机数
                        //var maxAbnormal = Convert.ToDouble(MaxAbnormalData);
                        //if (Convert.ToDouble(wr.Jz) > maxAbnormal) {

                        //    wr.Jz = Common.Utility.MatchHelper.NextDouble(maxAbnormal - 100, maxAbnormal).ToString("0.##");
                        //}

                        var maxVal = MaxAbnormalData.TryGetDecimal();
                        if (wr.Jz.TryGetDecimal() > maxVal)
                        {
                            var lowVal = maxVal * 0.95m;
                            var upVal = maxVal * 0.999m;
                            wr.Jz = Common.Utility.MatchHelper.NextDouble(lowVal, upVal).ToString("0.##");
                        }
                    }

                    DataRow row = dt.NewRow();

                    row[AppSection.Settings["_bh"].Value] = wr.Bh;
                    //row["超载"] = wr.IsLimit ? "是" : "否";
                    //row[AppSection.Settings["_weighName"].Value] = wr.WeighName;
                    //row[AppSection.Settings["_weigh2Name"].Value] = wr.Weigh2Name;
                    //row["是否遮挡"] = wr.IsCover ? "是" : "否";
                    //row["支付方式"] = wr.IsPay == 1 ? "电子支付" : wr.IsPay == 2 ? "线下支付" : wr.IsPay == 3 ? "储值支付" : wr.IsPay == 4 ? "免费放行" : "未支付";
                    foreach (var item in SelectedItems)
                    {
                        if (item == AppSection.Settings["_kh"].Value)
                        {
                            if (CustomerList.Count > 0 && wr.Kh != null && wr.Kh != "")
                                row[item] = CustomerList.FirstOrDefault(c => c.Name == wr.Kh)?.Name;
                        }

                        if (item == AppSection.Settings["_isLimit"].Value)
                        {
                            row[item] = wr.IsLimit ? "是" : "否";
                        }
                        if (item == AppSection.Settings["_isCover"].Value)
                        {
                            row[item] = wr.IsCover.GetValueOrDefault() ? "是" : "否";
                        }
                        if (item == AppSection.Settings["_isPay"].Value)
                        {
                            row[item] = wr.IsPay == 1 ? "电子支付" : wr.IsPay == 2 ? "线下支付" : wr.IsPay == 3 ? "储值支付" : wr.IsPay == 4 ? "免费放行" : "未支付";
                        }
                        if (item == AppSection.Settings["_iccard"].Value)
                        {
                            row[item] = wr.ICCard;
                        }
                        if (item == AppSection.Settings["_fhdw"].Value)
                        {
                            row[item] = wr.Fhdw;
                        }

                        if (item == AppSection.Settings["_weighName"].Value)
                        {
                            if (WeighNameList.Count > 0 && wr.WeighName != null)
                                row[item] = wr.WeighName;
                        }
                        if (item == AppSection.Settings["_weigh2Name"].Value)
                        {
                            if (Weigh2NameList.Count > 0 && wr.Weigh2Name != null)
                                row[item] = wr.Weigh2Name;// Weigh2NameList.SingleOrDefault(c => c.PlateNo == wr.Ch)?.PlateNo;
                        }

                        if (item == AppSection.Settings["_ch"].Value)
                        {
                            if (CarList.Count > 0 && wr.Ch != null)
                                row[item] = CarList.SingleOrDefault(c => c.PlateNo == wr.Ch)?.PlateNo;
                        }
                        if (item == AppSection.Settings["_wz"].Value)
                        {
                            //if (GoodsList.Count > 0 && wr.Wz != null && wr.Wz != "")
                            //    row[item] = GoodsList.FirstOrDefault(g => g.Name == wr.Wz)?.Name;
                            row[item] = wr.Wz;
                        }

                        if (item == AppSection.Settings["_je"].Value)
                        {
                            if (!string.IsNullOrWhiteSpace(wr.Je))
                                row[item] = wr.Je.TryGetDecimal();
                        }
                        if (item == AppSection.Settings["_dj"].Value)
                        {
                            row[item] = wr.GoodsPrice;
                        }
                        if (item == AppSection.Settings["_mz"].Value)
                        {
                            if (!string.IsNullOrWhiteSpace(wr.Mz))
                                row[item] = wr.Mz.TryGetDecimal();
                        }
                        if (item == AppSection.Settings["_mzrq"].Value)
                        {
                            row[item] = wr.Mzrq;
                        }
                        if (item == AppSection.Settings["_mzsby"].Value)
                        {
                            row[item] = wr.Mzsby;
                        }
                        if (item == AppSection.Settings["_pz"].Value)
                        {
                            if (!string.IsNullOrWhiteSpace(wr.Pz))
                                row[item] = wr.Pz.TryGetDecimal();
                        }
                        if (item == AppSection.Settings["_pzrq"].Value)
                        {
                            row[item] = wr.Pzrq;
                        }
                        if (item == AppSection.Settings["_pzsby"].Value)
                        {
                            row[item] = wr.Pzsby;
                        }
                        if (item == AppSection.Settings["_jz"].Value)
                        {
                            if (!string.IsNullOrWhiteSpace(wr.Jz))
                                row[item] = wr.Jz.TryGetDecimal();

                            try
                            {
                                SelectedTotalJz += wr.Jz.TryGetDecimal();
                            }
                            catch { }
                        }
                        if (item == AppSection.Settings["_jzrq"].Value)
                        {
                            row[item] = wr.Jzrq;
                        }
                        if (item == AppSection.Settings["_kz"].Value)
                        {
                            if (!String.IsNullOrWhiteSpace(wr.Kz))
                                row[item] = wr.Kz.TryGetDecimal();
                        }
                        if (item == AppSection.Settings["_kl"].Value)
                        {
                            row[item] = wr.Kl;
                        }
                        if (item == AppSection.Settings["_sz"].Value)
                        {
                            if (!String.IsNullOrWhiteSpace(wr.Sz))
                                row[item] = wr.Sz.TryGetDecimal();

                            try
                            {
                                SelectedTotalSz += wr.Sz.TryGetDecimal();
                            }
                            catch { }
                        }
                        if (item == AppSection.Settings["_bz"].Value)
                        {
                            row[item] = wr.Bz;
                        }
                        if (item == AppSection.Settings["_by1"].Value)
                        {
                            row[item] = wr.By1;
                        }
                        if (item == AppSection.Settings["_by2"].Value)
                        {
                            row[item] = wr.By2;
                        }
                        if (item == AppSection.Settings["_by3"].Value)
                        {
                            row[item] = wr.By3;
                        }
                        if (item == AppSection.Settings["_by4"].Value)
                        {
                            row[item] = wr.By4;
                        }
                        if (item == AppSection.Settings["_by5"].Value)
                        {
                            row[item] = wr.By5;
                        }
                        if (item == AppSection.Settings["_by6"].Value)
                        {
                            row[item] = wr.By6;
                        }
                        if (item == AppSection.Settings["_by7"].Value)
                        {
                            row[item] = wr.By7;
                        }
                        if (item == AppSection.Settings["_by8"].Value)
                        {
                            row[item] = wr.By8;
                        }
                        if (item == AppSection.Settings["_by9"].Value)
                        {
                            row[item] = wr.By9;
                        }
                        if (item == AppSection.Settings["_by10"].Value)
                        {
                            row[item] = wr.By10;
                        }
                        if (item == AppSection.Settings["_by11"].Value)
                        {
                            row[item] = wr.By11;
                        }
                        if (item == AppSection.Settings["_by12"].Value)
                        {
                            row[item] = wr.By12;
                        }
                        if (item == AppSection.Settings["_by13"].Value)
                        {
                            row[item] = wr.By13;
                        }
                        if (item == AppSection.Settings["_by14"].Value)
                        {
                            row[item] = wr.By14;
                        }
                        if (item == AppSection.Settings["_by15"].Value)
                        {
                            row[item] = wr.By15;
                        }
                        if (item == AppSection.Settings["_by16"].Value)
                        {
                            row[item] = wr.By16;
                        }
                        if (item == AppSection.Settings["_by17"].Value)
                        {
                            row[item] = wr.By17;
                        }
                        if (item == AppSection.Settings["_by18"].Value)
                        {
                            row[item] = wr.By18;
                        }
                        if (item == AppSection.Settings["_by19"].Value)
                        {
                            row[item] = wr.By19;
                        }
                        if (item == AppSection.Settings["_by20"].Value)
                        {
                            row[item] = wr.By20;
                        }
                        if (item == AppSection.Settings["_gblx"].Value)
                        {
                            row[item] = wr.Gblx;
                        }
                        if (item == AppSection.Settings["_axleNum"].Value)
                        {
                            row[item] = wr.AxleNum;
                        }
                        if (item == AppSection.Settings["_kh2"].Value)
                        {
                            row[item] = wr.Kh2;
                        }
                        if (item == AppSection.Settings["_kh3"].Value)
                        {
                            row[item] = wr.Kh3;
                        }
                        if (item == AppSection.Settings["_goodsSpec"].Value)
                        {
                            row[item] = wr.GoodsSpec;
                        }

                        //2022-11-03新增字段显示
                        if (item == AppSection.Settings["_driver"].Value)
                        {
                            row[item] = wr.Driver;
                        }
                        if (item == AppSection.Settings["_driverPhone"].Value)
                        {
                            row[item] = wr.DriverPhone;
                        }
                        if (item == AppSection.Settings["_entryTime"].Value)
                        {
                            row[item] = wr.EntryTime;
                        }
                        if (item == AppSection.Settings["_zflsh"].Value)
                        {
                            row[item] = wr.Zflsh;
                        }
                        if (item == AppSection.Settings["_zfje"].Value)
                        {
                            row[item] = wr.Zfje;
                        }
                        if (item == AppSection.Settings["_zfsj"].Value)
                        {
                            row[item] = wr.Zfsj;
                        }
                        //log.Debug("QueryList 修改列类型66666:" + WList.Count);
                        if (item == AppSection.Settings["_limitType"].Value)
                        {
                            row[item] = wr.LimitType;
                        }
                        if (item == AppSection.Settings["_limitedValue"].Value)
                        {
                            row[item] = wr.LimitedValue;
                        }
                        if (item == AppSection.Settings["_serialNumber"].Value)
                        {
                            row[item] = wr.SerialNumber;
                        }
                    }
                    dt.Rows.Add(row);
                }
                //把datatable set到属性RecordDT
                RecordDT = dt;
                SelectedTotalWeighingCount = dt.Rows.Count;

                StatusBar = string.Format("查询到{0}条符合条件的记录", SelectedTotalWeighingCount);
            }
            catch (Exception ex)
            {
                log.Debug("QueryList error:" + ex.Message);
                log.Info("QueryList error:" + ex.Message);
            }
        }

        public void PrintList()
        {
            if (RecordDT == null)
            {
                StatusBar = "当前查询列表为空";
                return;
            }

            //设置列宽
            var columnWidths = new List<double>();
            for (int i = 0; i < RecordDT.Columns.Count; i++)
            {
                double columnWidth = 70;
                if (RecordDT.Columns[i].ColumnName == AppSection.Settings["_bh"].Value)
                {
                    columnWidth = 100;
                }
                if (RecordDT.Columns[i].ColumnName == AppSection.Settings["_kh"].Value)
                {
                    columnWidth = 80;
                }
                if (RecordDT.Columns[i].ColumnName == AppSection.Settings["_ch"].Value)
                {
                    columnWidth = 80;
                }
                if (RecordDT.Columns[i].ColumnName == AppSection.Settings["_mzrq"].Value || RecordDT.Columns[i].ColumnName == AppSection.Settings["_pzrq"].Value)
                {
                    columnWidth = 120;
                }
                if (RecordDT.Columns[i].ColumnName == AppSection.Settings["_mzsby"].Value || RecordDT.Columns[i].ColumnName == AppSection.Settings["_pzsby"].Value)
                {
                    columnWidth = 80;
                }
                if (RecordDT.Columns[i].ColumnName == AppSection.Settings["_bz"].Value)
                {
                    columnWidth = 100;
                }
                if (RecordDT.Columns[i].ColumnName == AppSection.Settings["_weighName"].Value)
                {
                    columnWidth = 80;
                }
                if (RecordDT.Columns[i].ColumnName == AppSection.Settings["_weigh2Name"].Value)
                {
                    columnWidth = 80;
                }

                columnWidths.Add(columnWidth);
            }

            var ht = new ListHeaderTemplate();
            var headerTemplate = XamlWriter.Save(ht);
            #region 替换总计关键字
            headerTemplate = headerTemplate.Replace("@Company", AppSection.Settings["CompanyName"].Value);
            headerTemplate = headerTemplate.Replace("@StartDate", ((DateTime)StartDate).ToString("yyyy/MM/dd")).Replace("@EndDate", ((DateTime)EndDate).ToString("yyyy/MM/dd"));
            if (SelectedCar != null)
            {
                headerTemplate = headerTemplate.Replace("@PlateNo", SelectedCar.PlateNo);
            }
            else
            {
                headerTemplate = headerTemplate.Replace("@PlateNo", "全部");
            }
            if (SelectedCustomer != null)
            {
                headerTemplate = headerTemplate.Replace("@Customer", SelectedCustomer.Name);
            }
            else
            {
                headerTemplate = headerTemplate.Replace("@Customer", "全部");
            }
            if (SelectedGoods != null)
            {
                headerTemplate = headerTemplate.Replace("@Goods", SelectedGoods.Name);
            }
            else
            {
                headerTemplate = headerTemplate.Replace("@Goods", "全部");
            }
            headerTemplate = headerTemplate.Replace("@TotalWeighingCount", SelectedTotalWeighingCount.ToString());
            headerTemplate = headerTemplate.Replace("@TotalJz", SelectedTotalJz.ToString() + " " + WeighingUnit);
            if (TemplateFieldDic.ContainsKey("_sz"))
            {
                headerTemplate = headerTemplate.Replace("@TotalSz", "总实重：" + SelectedTotalSz.ToString() + " " + WeighingUnit);
            }
            else
            {
                headerTemplate = headerTemplate.Replace("@TotalSz", "");
            }
            #endregion
            var printControl = PrintControlFactory.Create(RecordDT, columnWidths, headerTemplate);
            printControl.ShowPrintPreview();
        }

        public void ExportList()
        {
            if (RecordDT == null)
            {
                StatusBar = "当前查询列表为空";
                return;
            }

            //使用DataTable数据新建excle表格
            Workbook workbook = new Workbook();
            Worksheet worksheet = workbook.Worksheets[0];
            worksheet.Name = "称重记录";

            ImportTableOptions importOptions = new ImportTableOptions();
            importOptions.IsFieldNameShown = true;
            importOptions.IsHtmlString = true;

            worksheet.Cells.ImportData(RecordDT, 0, 0, importOptions);

            #region 增加表头、格式

            Aspose.Cells.Style blodStyle = workbook.CreateStyle();
            blodStyle.Font.IsBold = true;
            StyleFlag flag = new StyleFlag();
            flag.FontBold = true;

            Aspose.Cells.Style headerStyle = workbook.CreateStyle();
            headerStyle.Font.IsBold = true;
            headerStyle.Font.Size = 16;
            headerStyle.HorizontalAlignment = TextAlignmentType.Center;

            worksheet.Cells.Rows[0].ApplyStyle(blodStyle, flag);

            worksheet.Cells.InsertRows(0, 5);

            worksheet.Cells.Merge(0, 0, 1, (RecordDT.Columns.Count > 8) ? RecordDT.Columns.Count : 8);
            worksheet.Cells["A1"].PutValue(AppSection.Settings["CompanyName"].Value + "称重明细列表");
            worksheet.Cells["A1"].SetStyle(headerStyle);
            worksheet.Cells["A2"].PutValue("统计日期");
            worksheet.Cells["A2"].SetStyle(blodStyle);
            worksheet.Cells.Merge(1, 1, 1, 5);
            worksheet.Cells["B2"].PutValue(((DateTime)StartDate).ToString("yyyy/MM/dd") + " ~ " + ((DateTime)EndDate).ToString("yyyy/MM/dd"));
            worksheet.Cells["G2"].PutValue("重量单位");
            worksheet.Cells["G2"].SetStyle(blodStyle);
            worksheet.Cells["H2"].PutValue(WeighingUnit);
            worksheet.Cells["A3"].PutValue("车号");
            worksheet.Cells["A3"].SetStyle(blodStyle);
            worksheet.Cells["B3"].PutValue((SelectedCar != null) ? SelectedCar.PlateNo : "全部");
            worksheet.Cells["D3"].PutValue("客户");
            worksheet.Cells["D3"].SetStyle(blodStyle);
            worksheet.Cells["E3"].PutValue((SelectedCustomer != null) ? SelectedCustomer.Name : "全部");
            worksheet.Cells["G3"].PutValue("物资");
            worksheet.Cells["G3"].SetStyle(blodStyle);
            worksheet.Cells["H3"].PutValue((SelectedGoods != null) ? SelectedGoods.Name : "全部");
            worksheet.Cells["A4"].PutValue("总车次");
            worksheet.Cells["A4"].SetStyle(blodStyle);
            worksheet.Cells["B4"].PutValue(SelectedTotalWeighingCount);
            worksheet.Cells["D4"].PutValue("总净重");
            worksheet.Cells["D4"].SetStyle(blodStyle);
            worksheet.Cells["E4"].PutValue(SelectedTotalJz);
            if (TemplateFieldDic.ContainsKey("_sz"))
            {
                worksheet.Cells["G4"].PutValue("总实重");
                worksheet.Cells["G4"].SetStyle(blodStyle);
                worksheet.Cells["H4"].PutValue(SelectedTotalSz);
            }

            worksheet.AutoFitColumns();
            #endregion

            workbook.Save(Globalspace._weighingRecordTempPath, SaveFormat.Xlsx);

            //删掉aspose的试用版信息，删掉临时文件
            XSSFWorkbook book;
            using (FileStream file = new FileStream(Globalspace._weighingRecordTempPath, FileMode.Open, FileAccess.Read))
            {
                book = new XSSFWorkbook(file);
            }
            //book.RemoveSheetAt(1);
            File.Delete(Globalspace._weighingRecordTempPath);

            //打开保存文件对话框，保存称重记录
            CommonSaveFileDialog dialog = new CommonSaveFileDialog();
            dialog.DefaultFileName = "称重记录_" + DateTime.Now.ToString("yyyyMMdd");
            dialog.DefaultExtension = "xlsx";
            dialog.AlwaysAppendDefaultExtension = true;
            dialog.Filters.Add(new CommonFileDialogFilter("Excel 工作簿", ".xlsx"));

            if (dialog.ShowDialog() == CommonFileDialogResult.Ok)
            {
                FileStream file = new FileStream(dialog.FileName, FileMode.Create);
                book.Write(file);
                file.Close();
                book.Close();
                StatusBar = "导出成功！称重记录文件路径：" + dialog.FileName;
            }
        }

        public void DeleteList()
        {
            var vm = new PasswordViewModel(windowManager, 3);
            bool? result = windowManager.ShowDialog(vm);

            if (result.GetValueOrDefault(true))
            {
                foreach (var wr in WList)
                {
                    SQLDataAccess.DeleteWeighingRecord(wr);
                    //上传平台
                    var obj = Common.Data.SQLDataAccess.GetWeighingRecordByBh(wr.Bh);
                    if (obj != null)
                    {
                        Common.SyncData.Instal.ModifyWeinightRecord(obj, Common.Api.edit);
                    }
                }
                string info = string.Format("已删除{0}条记录", WList.Count);
                QueryList();
                SetBtns();
                StatusBar = info;
            }
        }

        public void OpenPzReport()
        {
            if (SelectedRecrod == null)
            {
                StatusBar = "请选择一条记录";
                return;
            }
            var bh = SelectedRecrod.Row.ItemArray[0].ToString();
            var record = WList.Find(w => w.Bh == bh);
            if (this.windowManager != null && record != null)
            {
                var viewModel = new PzReportViewModel(this.windowManager, record);
                //var result = this.windowManager.ShowDialog(viewModel);
                this.windowManager.ShowWindow(viewModel);
            }

        }

        /// <summary>
        /// 一键补传所有
        /// </summary>
        public void ReUploadAll()
        {
            var progressView = new ReuploadAllProgressViewModel(windowManager, NotUploadedRecords);
            windowManager.ShowDialog(progressView);

            NotUploadedRecords = SQLDataAccess.LoadWeighingRecordByUploadFlag(false);

            ReUploadButtonVisible = NotUploadedRecords.Count > 0
                 ? Visibility.Visible : Visibility.Collapsed;
        }

        public void ReUpload()
        {
            if (SelectedRecrod == null)
            {
                MessageBox.Show("请选择一条记录");
                return;
            }
            var Bh = SelectedRecrod.Row.ItemArray[0].ToString();
            var record = WList.FirstOrDefault(w => w.Bh == Bh);

            if (Common.Platform.PlatformManager.Instance.IsDefault) return;

            string channelCode = Common.Utility.SettingsHelper.AWSV2Settings.Settings["platformChannel"]?.Value ?? string.Empty;
            string imgDirectory = string.Empty;
            string videoDirectory = string.Empty;
            Common.Models.WeighingRecordModel obj
                = AJUtil.TryGetJSONObject<Common.Models.WeighingRecordModel>(AJUtil.AJSerializeObject(record));
            
            // 上传第一次
            try
            {
                Common.Platform.PlatformManager.Instance.Current.UploadWeighingData(obj, channelCode, imgDirectory, videoDirectory);
            }
            catch (Exception e)
            {
                MessageBox.Show($"一次称重上传失败：{e.Message}");
                return;
            }

            // 上传第二次
            obj.Mz = record.Pz;
            obj.WeighName = record.Weigh2Name;
            obj.Mzrq = record.Pzrq;
            try
            {
                Common.Platform.PlatformManager.Instance.Current.UploadWeighingData(obj, channelCode, imgDirectory, videoDirectory);
            }
            catch (Exception e)
            {
                MessageBox.Show($"二次称重上传失败：{e.Message}");
                return;
            }

            MessageBox.Show("上传成功！");

        }


        public void UpdateSelected()
        {
            if (SelectedRecrod == null)
            {
                StatusBar = "请选择一条记录";
            }
            else
            {
                var Bh = SelectedRecrod.Row.ItemArray[0].ToString();
                var Record = WList.Find(w => w.Bh == Bh);

                var validator = new WeighingRecordViewModelValidator();
                var validatorAdapter = new FluentModelValidator<WeighingRecordViewModel>(validator);

                var viewModel = new WeighingRecordViewModel(validatorAdapter, TemplateFieldDic, this.windowManager, Record);
                var result = this.windowManager.ShowDialog(viewModel);
                if (result.GetValueOrDefault(true))
                {
                    QueryList();
                    SetBtns();
                    StatusBar = "修改记录完成";
                }
            }
        }

        public void DeleteSelected()
        {
            try
            {
                if (SelectedRecrod == null)
                {
                    StatusBar = "请选择一条记录";
                    return;
                }

                {
                    //var vm = new PasswordViewModel(windowManager, 3);
                    bool? result = true;// windowManager.ShowDialog(vm);

                    if (result.GetValueOrDefault(true))
                    {
                        var Bh = SelectedRecrod.Row.ItemArray[0].ToString();
                        var Record = WList.Find(w => w.Bh == Bh);

                        if (DelBtnText == "作废选中")
                        {
                            SQLDataAccess.DeleteWeighingRecord(Record);
                            StatusBar = "选中记录已删除";
                            DelBtnText = "取消作废";
                        }
                        else//取消作废
                        {
                            SQLDataAccess.ResetWeighingRecord(Record);
                            StatusBar = "选中记录已恢复";
                            DelBtnText = "作废选中";
                        }

                        QueryList();
                        SetBtns();

                        //上传平台
                        var obj = Common.Data.SQLDataAccess.GetWeighingRecordByBh(Bh);
                        if (obj != null)
                        {
                            Common.SyncData.Instal.ModifyWeinightRecord(obj, Common.Api.edit);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                log.Info("DeleteSelected error:" + ex.Message);
            }

        }

        #region 分页逻辑以及属性

        /// <summary>
        /// 索引信息集合
        /// </summary>
        public ObservableCollection<WeighingRecord.Models.Custom.PagerHandle> Indexs { get; set; } = new ObservableCollection<Models.Custom.PagerHandle>();

        public System.Windows.Style LeftStyle { get; set; } = (System.Windows.Style)Application.Current.Resources["Button TotalStyle"];

        public System.Windows.Style RightStyle { get; set; } = (System.Windows.Style)Application.Current.Resources["Button TotalStyle"];

        public ObservableCollection<WeighingRecord.Models.Custom.ComboItem> PageSizeItems { get; set; } = new ObservableCollection<Models.Custom.ComboItem>
        {
            new Models.Custom.ComboItem(){ Name="10条/页", Value=10 },
            new Models.Custom.ComboItem(){ Name="100条/页", Value=100 },
            new Models.Custom.ComboItem(){ Name="500条/页", Value=500 },
            new Models.Custom.ComboItem(){ Name="1000条/页", Value=1000 },
            new Models.Custom.ComboItem(){ Name="2000条/页", Value=2000 },
            new Models.Custom.ComboItem(){ Name="5000条/页", Value=5000 },
            new Models.Custom.ComboItem(){ Name="10000条/页", Value=10000 },
        };

        WeighingRecord.Models.Custom.ComboItem _SelectedPageSizeItems;
        public WeighingRecord.Models.Custom.ComboItem SelectedPageSizeItems
        {
            get
            {
                return _SelectedPageSizeItems;
            }
            set
            {
                if (value != null)
                {
                    _SelectedPageSizeItems = value;
                    PageCount = int.Parse(_SelectedPageSizeItems.Value.ToString());
                    Query();
                }
            }
        }

        /// <summary>
        /// 当前选中的索引信息
        /// </summary>
        public int CurrentIndex { get; set; } = 1;
        /// <summary>
        /// 页总数
        /// </summary>
        public int Pages { get; set; }
        /// <summary>
        /// 有效的索引按钮个数，不包含（...，最有一页这2个按钮）
        /// </summary>
        public int IndexButs { get; set; } = 3;
        /// <summary>
        /// 一页显示的行数
        /// </summary>
        public int PageCount { get; set; } = 1;
        /// <summary>
        /// 数据的总数
        /// </summary>
        public int DataCount { get; set; }


        public void LeftSide(object indexStr)
        {
            LeftStyle = (System.Windows.Style)Application.Current.Resources["YellowStyle"];
            RightStyle = (System.Windows.Style)Application.Current.Resources["Button TotalStyle"];

            var moveIndex = CurrentIndex - 1;
            if (moveIndex < 1) return;

            CurrentIndex = moveIndex;

            SetBtns();
            SelectedPage(moveIndex.ToString());

        }

        public void RightSide(object indexStr)
        {
            var moveIndex = CurrentIndex + 1;
            if (moveIndex > Pages) return;

            RightStyle = (System.Windows.Style)Application.Current.Resources["YellowStyle"];
            LeftStyle = (System.Windows.Style)Application.Current.Resources["Button TotalStyle"];

            CurrentIndex = moveIndex;

            SetBtns();
            SelectedPage(moveIndex.ToString());

        }

        public void SelectedPage(object indexStr)
        {
            string str = indexStr.ToString();

            if (string.IsNullOrEmpty(str)) return;

            if (str != "...")
            {
                CurrentIndex = int.Parse(str);
            }

            if (str == "...")
            {
                var maxIndex = Indexs.Where(p => p.IndexStr != "..." && p.IndexStr != Pages.ToString()).Max(p => int.Parse(p.IndexStr));
                CurrentIndex = maxIndex;
                SetBtns();
            }
            else
            {
                var indexInfo = Indexs.FirstOrDefault(p => p.IndexStr == str);

                Indexs.ToList().ForEach(e => { e.ControlStyle = (System.Windows.Style)Application.Current.Resources["Button TotalStyle"]; });

                indexInfo.ControlStyle = (System.Windows.Style)Application.Current.Resources["YellowStyle"];

                QueryList();
                if (CurrentIndex == Pages)
                {
                    SetBtns();
                }
            }

        }

        private void SetBtns()
        {
            Indexs.Clear();

            if (CurrentIndex < 1 || CurrentIndex > Pages) return;

            if (Pages <= IndexButs)
            {
                for (int i = 1; i <= Pages; i++)
                {
                    if (i == CurrentIndex)
                    {
                        Indexs.Add(new Models.Custom.PagerHandle() { IndexStr = i.ToString(), ControlStyle = (System.Windows.Style)Application.Current.Resources["YellowStyle"] });
                        continue;
                    }
                    Indexs.Add(new Models.Custom.PagerHandle() { IndexStr = i.ToString(), ControlStyle = (System.Windows.Style)Application.Current.Resources["Button TotalStyle"] });
                }

            }
            else
            {
                int i = CurrentIndex;

                for (; i <= Pages; i++)
                {
                    if (i - CurrentIndex >= IndexButs) break;

                    if (i == CurrentIndex)
                    {
                        Indexs.Add(new Models.Custom.PagerHandle() { IndexStr = i.ToString(), ControlStyle = (System.Windows.Style)Application.Current.Resources["YellowStyle"] });
                        continue;
                    }
                    Indexs.Add(new Models.Custom.PagerHandle() { IndexStr = i.ToString(), ControlStyle = (System.Windows.Style)Application.Current.Resources["Button TotalStyle"] });
                }
                if (i < Pages)
                {
                    Indexs.Add(new Models.Custom.PagerHandle() { IndexStr = "...", ControlStyle = (System.Windows.Style)Application.Current.Resources["Button TotalStyle"] });
                    Indexs.Add(new Models.Custom.PagerHandle() { IndexStr = Pages.ToString(), ControlStyle = (System.Windows.Style)Application.Current.Resources["Button TotalStyle"] });
                }
                else if (Indexs.Count < IndexButs)//如果没有预定的IndexButs个按钮，那么就要补齐少的
                {
                    int minIdex = Indexs.Min(p => int.Parse(p.IndexStr));
                    for (int j = Indexs.Count; j < IndexButs; j++)
                    {
                        minIdex--;
                        Indexs.Insert(0, new Models.Custom.PagerHandle() { IndexStr = (minIdex).ToString(), ControlStyle = (System.Windows.Style)Application.Current.Resources["Button TotalStyle"] });
                    }
                }
            }
        }

        public void Query()
        {
            CurrentIndex = 1;
            QueryList();
            SetBtns();
        }

        #endregion

        public void PrintSelected()
        {
            if (SelectedRecrod == null)
            {
                StatusBar = "请选择一条记录";
            }
            else
            {
                var Bh = SelectedRecrod.Row.ItemArray[0].ToString();
                var Record = WList.Find(w => w.Bh == Bh);

                Record.Dyrq = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                PrintHelper.PrintImg(Record, Worksheet);

                log.Info("补充打印磅单:" + Record.Bh);
            }
        }

        public void InsertItem()
        {
            var validator = new WeighingRecordViewModelValidator();
            var validatorAdapter = new FluentModelValidator<WeighingRecordViewModel>(validator);

            var viewModel = new WeighingRecordViewModel(validatorAdapter, TemplateFieldDic, this.windowManager, null);
            var result = this.windowManager.ShowDialog(viewModel);
            if (result.GetValueOrDefault(true))
            {
                QueryList();
                SetBtns();
                StatusBar = "新增记录完成";
            }
        }

        public void OpenPicFolder()
        {
            string path = ((AppSettingsSection)ConfigurationManager.OpenExeConfiguration("ZXLPR.exe").GetSection("appSettings")).Settings["LPRSavePath"].Value;
            //string path = Environment.CurrentDirectory + "/Snap/";
            if (SelectedRecrod != null)
            {
                //string path2 = path +"//"+ SelectedRecrod.Row.ItemArray[0].ToString();
                var record = Common.Data.SQLDataAccess.GetWeighingRecordByBh(SelectedRecrod.Row.ItemArray[0].ToString());
                if (record == null)
                {
                    if (Directory.Exists(path)) Process.Start(path);
                    return;
                }

                string path2 = path + "\\" + record.Ch + "\\" + SelectedRecrod.Row.ItemArray[0].ToString();
                if (Directory.Exists(path2))
                {
                    Globalspace.ImagsSource = path2;
                    //Process.Start(path2);
                    windowManager.ShowDialog(new PicListViewModel(windowManager, path2));
                }
                //else if (Directory.Exists(path))
                //{
                //    Process.Start(path);
                //}
                Globalspace.ImagsSource = string.Empty;
            }
            else
            {
                if (Directory.Exists(path)) Process.Start(path);
            }

        }
    }

    public class WeighingRecordComparer : IEqualityComparer<WeighingRecordModel>
    {
        public bool Equals(WeighingRecordModel x, WeighingRecordModel y)
        {
            return x.Bh == y.Bh;
        }

        public int GetHashCode(WeighingRecordModel obj)
        {
            //return obj.GetHashCode();
            return 1;
        }
    }
}
